package com.example.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class ObjectUtil
{
    public static void setValueByReflect(Object object, Map<String, Object> values)
    {
        if (object == null)
            return;

        if (values == null || values.isEmpty())
            return;

        Class clazz = object.getClass();

        Field[] fields = clazz.getDeclaredFields();
        if (fields.length == 0)
            return;

        for (Field field : fields)
        {
            String name = field.getName();
            Object v = values.get(name);
            if(v == null)
                continue;

            String methodName = "set" + toUpperCaseFirstOne(name);
            try
            {
                Method declaredMethod = clazz.getDeclaredMethod(methodName, field.getType());
                declaredMethod.setAccessible(true);
                declaredMethod.invoke(object, v);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e)
            {
                e.printStackTrace();
            }
        }
    }

    private static String toUpperCaseFirstOne(String s)
    {
        if (Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return Character.toUpperCase(s.charAt(0)) + s.substring(1);
    }
}
